<?php
namespace app\api\controller;

use app\common\controller\BasicApi;
use app\common\model\OrderLogModel;
use app\common\model\OrderModel;
use app\common\model\OrderGoodsModel;
use app\common\model\GoodsModel;
use app\common\model\UserCouponModel;
use app\common\model\UserModel;
use think\Db;
use think\facade\Hook;

/**
 * 支付通知处理
 * Class Notify
 * @package app\store\controller\api
 */
class Notify extends BasicApi
{
    public $checkRequest = 'test';
    /**
     * 微信支付通知处理
     * @return string
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function wxpay()
    {
        $wechat = \We::WePayOrder(config('wechat.miniapp'));
        $notify = $wechat->getNotify();

        if ($notify['result_code'] == 'SUCCESS' && $notify['return_code'] == 'SUCCESS') {
            //查询订单信息
            $order = OrderModel::where(['trade_no'=>$notify['out_trade_no']])->find();
            if (empty($order)){
                $this->error('订单未找到！','',400);
            }
            //是否已经支付过
            if (!empty($order['pay_time']) && !empty($order['trade_no'] && $order['status']==ORDER_STATUS_PAY)){
                $this->error('订单已支付过！','',400);
                return $wechat->getNotifySuccessReply();
            }
            //支付成功后更改成状态
            OrderModel::where(['id'=>$order['id']])->update([
                'pay_time'=>date('Y-m-d H:i:s',time()),
                'status'=>ORDER_STATUS_ZITI
                ]);
            //只增加销量和改变商品状态，库存在下单时就减少了
            $goods_id = OrderGoodsModel::where('order_id',$order['id'])->value('goods_id');
            GoodsModel::where('id',$goods_id)->setInc('sales',1);
            //支付成功使用优惠券
            UserCouponModel::where('id',$order['coupon_id'])->delete();
            //找到用户id及昵称
            $user_id = OrderModel::where('id',$order['id'])->value('user_id');
            $user_name = UserModel::where('id',$user_id)->value('nickname');
            OrderLogModel::where('')->insert([
                'order_id'=>$order['id'],
                'operate_id'=>$user_id,
                'operate_name'=>$user_name,
                'content'=> '支付订单',
                'type'=> 1,
                'create_time'=>date('Y-m-d H:i:s',time())
            ]);
            return $wechat->getNotifySuccessReply();
        } else {
            $this->error('微信支付通知处理异常,订单id:'.$notify['out_trade_no'],'', 400);
        }
        return $wechat->getNotifySuccessReply();//获取微信支付通知回复内容
    }

}
